/**
 * $Id$
 */
package com.xtianzhuang.www.study2019.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import com.mysql.jdbc.StringUtils;


public class FileUtils {

	private static Log logger = LogFactory.getLog(FileUtils.class);


	public static boolean uploadFile(String url, int port, String username, String password, String path,
			String filename, InputStream input) {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			logger.debug("connect ftp: " + url + ":" + port);
			ftp.connect(url, port);// 连接FTP服务器
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			// logger.debug("login use: " + username + "," + password);
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			// logger.debug("login reply: " + reply);
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				// logger.error("ftp " + url + "," + port +": login fail!");
				return success;
			}
			if (!ftp.changeWorkingDirectory(path)) {
				ftp.makeDirectory(path);
			}
			if (ftp.changeWorkingDirectory(path)) {
				ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
				ftp.storeFile(filename, input);
				success = true;
			} else {
				// logger.error("ftp change path " + path + ", error");
			}
			input.close();
			ftp.logout();
		} catch (IOException e) {
			logger.error("uploadFile error: " + e.getMessage(), e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;
	}

	public static void makdir(String url, int port, String username, String password, String path) {
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			logger.debug("connect ftp: " + url + ":" + port);
			ftp.connect(url, port);// 连接FTP服务器
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			// logger.debug("login use: " + username + "," + password);
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			logger.debug("login reply: " + reply);
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				// logger.error("ftp " + url + "," + port + "," + username + "," + password + ": login fail!");
				return;
			}
			mkdirs(ftp, path);
			ftp.logout();
		} catch (IOException e) {
			logger.error("uploadFile error: " + e.getMessage(), e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
	}

	public static void mkdirs(FTPClient ftp, String path) throws IOException {
		if (path.endsWith("/")) {
			path = path.substring(0, path.length() - 1);
		}
		if (ftp.changeWorkingDirectory(path)) {
			return;
		}
		if ("/".equals(path)) {
			return;
		}
		int lastIndex = path.lastIndexOf("/");
		String parentPath = path.substring(0, lastIndex);
		if (!"/".equals(parentPath) && !StringUtils.isNullOrEmpty(parentPath)) {
			mkdirs(ftp, parentPath);
		}
		ftp.makeDirectory(path);
	}

	// SHA-1加密
	public static String calcSha1(byte[] data) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md;
		md = MessageDigest.getInstance("SHA-1");
		md.update(data);
		return convertToHex(md.digest());
	}

	private static String convertToHex(byte[] data) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < data.length; i++) {
			int halfbyte = (data[i] >>> 4) & 0x0F;
			int two_halfs = 0;
			do {
				if ((0 <= halfbyte) && (halfbyte <= 9))
					buf.append((char) ('0' + halfbyte));
				else
					buf.append((char) ('a' + (halfbyte - 10)));
				halfbyte = data[i] & 0x0F;
			} while (two_halfs++ < 1);
		}
		return buf.toString();
	}

}
